#include"Comm.hpp"

int main()
{
    key_t k = ftok(PATH_NAME.c_str(), PROJ_ID);
    if(k == -1)
    {
        Log("获取key值失败", Error) << "k = " << k << endl;
        exit(1);
    }
    Log("获取key值成功", Debug) << "k = " << k << endl;
    //sleep(3);

    int shmid = shmget(k, SIZE, 0);
    if(shmid == -1)
    {
        Log("获取共享内存失败", Warning) << endl;
        exit(2);
    }
    Log("获取共享内存成功", Debug) << "shmid = " << shmid << endl;
    //sleep(3);

    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    if(*shmaddr == -1)
    {
        Log("共享内存关联失败", Warning) << endl;
        exit(3);
    }
    Log("共享内存关联成功", Debug) << "shmid = " << shmid << endl;
    //sleep(10);

    // for(int i = 0; i < 5; ++i)
    // {
    //     snprintf(shmaddr, SIZE, "%d, snowdragon write, %d\n", getpid(), i);
    //     sleep(2);
    // }

    int fd = OpenFifo(FIFO_PATH_NAME, WRITE);

    while(true)
    {
        ssize_t s = read(0, shmaddr, SIZE - 1);         //留一个位置给\0
        if(s > 0)
        {
            shmaddr[s - 1] = '\0';
            WakeUp(fd);     //当有输入内容时才调用，否则Wait函数会出错
            if(strcmp(shmaddr, "quit") == 0)
                break;
        }
    }

    CloseFifo(fd);

    int ret = shmdt(shmaddr);
    if(ret == -1)
    {
        Log("共享内存去关联失败", Notice) << endl;
        exit(4);
    }
    Log("共享内存去关联成功", Debug) << "shmid = " << shmid << endl;

    return 0;
}